package pl.bristleback.chat.services;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import pl.bristleback.chat.exceptions.UserExistsException;
import pl.bristleback.chat.vo.User;

import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/**
 * //@todo class description
 * <p/>
 * Created on: 13.04.11 16:45 <br/>
 *
 * @author Paweł Machowski
 */
@Controller
public class UsersService {
  private static Logger log = Logger.getLogger(UsersService.class.getName());

  private final Set<User> users = Collections.synchronizedSet(new TreeSet<User>());

  public Set<User> getAllUsers() {
    return users;
  }

  public User getUserByConnectorId(String id) {
    synchronized (users) {
      for (User user : users) {
        if (user.getId().equals(id)) {
          return user;
        }
      }
    }
    return null;
  }

  public void removeUserByConnectorId(String id) {
    synchronized (users) {
      Iterator<User> iterator = users.iterator();
      while (iterator.hasNext()) {
        User next = iterator.next();
        if (next.getId().equals(id)) {
          iterator.remove();
          break;
        }
      }
    }
  }

  public void addUser(User newUser) throws UserExistsException {
    if (users.contains(newUser)) {
      throw new UserExistsException();
    }
    users.add(newUser);
  }


} 